
import './equipment.scss'
import { useState, useEffect } from 'react';
import { Form, Input, Button, Select, Table, Modal, Message, } from '@arco-design/web-react';
import mochaApi from '../../../API/mochaApi';

const FormItem = Form.Item;
const TextArea = Input.TextArea;
let customId = 0

const Equipment = () => {
  const [inputFrom] = Form.useForm()
  const [handleFrom] = Form.useForm()
  const [visible, setVisible] = useState(false);
  const pageSize = 5
  const [btnState, setBtnState] = useState(false)//第二个表格关闭按钮状态
  const [selData, setSelData] = useState([])

  //表头数据
  const columns = [
    {
      title: '序号',
      render: (col, record, index) => `${index + 1}`,
      align: 'center'
    },
    {
      title: '设备编号',
      dataIndex: 'equipmentNum',
    },
    {
      title: '设备类型',
      dataIndex: 'equipmentType',
    },
    {
      title: '运行状态',
      dataIndex: 'runningType',
    },
    {
      title: '所属位置',
      dataIndex: 'parkingName',
    },
    {
      title: '告警次数',
      dataIndex: 'warningTimes',
      render: (col, record) => {
        return <span className='tableBtn' onClick={() => tableBtn(record)}>【{record.warningTimes}】</span>
      }
    },
    {
      title: '最近告警时间',
      dataIndex: 'lastWarningTime',
    },
    {
      title: '告警级别',
      dataIndex: 'warningLevel',
      //0提醒  1通知  2提醒  3二级 4一级
      render: (col, record) => {
        if (record.warningLevel === 0) {
          return <span>提醒</span>
        } else if (record.warningLevel === 1) {
          return <span>通知</span>
        } else if (record.warningLevel === 2) {
          return <span>提醒</span>
        } else if (record.warningLevel === 3) {
          return <span>二级</span>
        } else if (record.warningLevel === 4) {
          return <span>一级</span>
        }
      }
    },
    {
      title: '处理状态',
      dataIndex: 'processStatus',
      //0--未处理 1--待处理 2--已处理  
      render: (col, record) => {
        if (record.processStatus === 0) {
          return <span>未处理</span>
        } else if (record.processStatus === 1) {
          return <span>待处理</span>
        } else if (record.processStatus === 2) {
          return <span>已处理</span>
        }
      }
    },
    {
      title: '操作',
      render: (col, record) => <span onClick={() => immediatelyModal(record)} className='handle'>立即处理</span>
    },
  ];
  //表格数据
  const [data, setData] = useState([])
  //获取第一个表格所有数据
  const getData = () => {
    mochaApi.getEquipment().then((res) => {
      if (res.code === 200) {
        setData(res.result)
      }
    })
  }
  useEffect(() => {
    getData()
  }, [])
  //第一个表格里面的表格-----------告警次数
  const tableBtn = (record) => {
    mochaApi.getTableBtn(record.equipmentId).then((res) => {
      if (res.code === 200) {
        setTableBtnData(res.result)
        setBtnState(true)
      }
    })
  }
  //第二个表格得关闭按钮
  const selectItemRightBtn = () => {
    setBtnState(false)
  }
  //表格里面的表格---表头
  const tableData = [
    {
      title: '编号',
      render: (col, record, index) => `${index + 1}`,
      align: 'center'
    },
    {
      title: '告警级别',
      dataIndex: 'warningLevel',
      //0提醒  1通知  2提醒  3二级 4一级
      render: (col, record) => {
        if (record.warningLevel === 0) {
          return <span>提醒</span>
        } else if (record.warningLevel === 1) {
          return <span>通知</span>
        } else if (record.warningLevel === 2) {
          return <span>提醒</span>
        } else if (record.warningLevel === 3) {
          return <span>二级</span>
        } else if (record.warningLevel === 4) {
          return <span>一级</span>
        }
      }
    },
    {
      title: '所属位置',
      dataIndex: 'parkingName',
    },
    {
      title: '设备类型',
      dataIndex: 'equipmentType',
    },
    {
      title: '设备编号',
      dataIndex: 'equipmentNum',
    },
    {
      title: '最近告警时间',
      dataIndex: 'warningTime',
    },
    {
      title: '状态',
      dataIndex: 'processStatus',
      //0--未处理 1--待处理 2--已处理  
      render: (col, record) => {
        if (record.processStatus === 0) {
          return <span>未处理</span>
        } else if (record.processStatus === 1) {
          return <span>待处理</span>
        } else if (record.processStatus === 2) {
          return <span>已处理</span>
        }
      }
    },
    {
      title: '处理人',
      dataIndex: 'userName',
    },
    {
      title: '处理时间',
      dataIndex: 'processTime',
    },
    {
      title: '处理结果',
      dataIndex: 'processResult',
    },
  ]
  //表格里面的表格---数据
  const [tableBtnData, setTableBtnData] = useState([])
  //查询按钮
  const queryBtn = () => {
    let value = inputFrom.getFieldsValue()
    let obj = {
      equipmentNum: value.equipmentNum === undefined ? '' : value.equipmentNum,
      equipmentType: value.equipmentType === undefined ? '' : value.equipmentType,
      parkingName: value.parkingName === undefined ? '' : value.parkingName,
      runningType: value.runningType === undefined ? '' : value.runningType,
    }
    mochaApi.queryEquipment(obj).then((res) => {
      setData(res.result)
    })
  }
  //重置按钮
  const resetBtn = () => {
    inputFrom.clearFields()
    getData()
  }

  //立即处理----显示
  const immediatelyModal = (value) => {
    setVisible(true)
    customId = value.equipmentId
    let year = new Date().getFullYear()
    let month;
    let day;
    if ((new Date().getMonth() + 1) < 10 || new Date().getDate() < 10) {
      month = '0' + (new Date().getMonth() + 1)
      day = '0' + new Date().getDate()
    } else {
      month = new Date().getMonth() + 1
      day = new Date().getDate()
    }
    let data = year + '-' + month + '-' + day
    handleFrom.setFieldValue('processTime', data)
  }
  //下拉框获取用户名
  const userNameForm = () => {
    let obj = []
    mochaApi.getUserName().then((res) => {
      if (res.code === 200) {
        for (let i = 0; i < res.result.length; i++) {
          obj.push({
            label: res.result[i].label,
            value: res.result[i].label
          })
          setSelData(obj)
        }
      }
    })
  }
  //立即处理----确定
  const handleBtn = () => {
    let value = handleFrom.getFieldsValue()
    value.equipmentId = customId
    verification()
    mochaApi.immediateProcessing(value).then((res) => {
      if (res.code === 200) {
        setVisible(false)
        getData()
        Message.success('处理成功')
      } else {
        Message.error('处理失败')
      }
    })

  }
  //表单校验
  async function verification() {
    try {
      await handleFrom.validate()
    } catch (e) {
      console.log(e);
    }
  }

  return <div className='equipment'>
    <div className='formBox'>
      <Form form={inputFrom} className='formBoxFrom' layout='inline' colon size='default'>
        <FormItem label='设备编号' field='equipmentNum'>
          <Input placeholder='请输入' />
        </FormItem>
        <FormItem label='设备类型' field='equipmentType'>
          <Select
            placeholder='请选择'
            options={[
              {
                label: '摄像头',
                value: '摄像头',
              },
              {
                label: '网关设备',
                value: '网关设备',
              },
              {
                label: 'ETC设备',
                value: 'ETC设备',
              },
              {
                label: '闸机',
                value: '闸机'
              },
              {
                label: '车辆感应器',
                value: '车辆感应器'
              },
              {
                label: '停车场控制机',
                value: '停车场控制机'
              },
              {
                label: '通讯适配器',
                value: '通讯适配器'
              },
              {
                label: '远距离卡读感器',
                value: '远距离卡读感器'
              },
              {
                label: '自动吐卡机',
                value: '自动吐卡机'
              }
            ]}
            allowClear
          />
        </FormItem>
        <FormItem label='运行状态' field='runningType'>
          <Select
            placeholder='请选择'
            options={[
              {
                label: '正常',
                value: '正常',
              },
              {
                label: '离线',
                value: '离线',
              },
              {
                label: '告警',
                value: '告警',
              },
            ]}
            allowClear
          />
        </FormItem>
        <FormItem label='所属位置' field='parkingName'>
          <Input placeholder='请输入' />
        </FormItem>
      </Form>
      <div className='export'>
        {btnState ? <Button type='primary' onClick={selectItemRightBtn}>关闭</Button> : null}
        <Button type='primary' onClick={queryBtn}>查询</Button>
        <Button type='outline' onClick={resetBtn}>重置</Button>
      </div>
    </div>
    {btnState ? null : <Table border borderCell
      rowKey={(record) => record.equipmentId}
      columns={columns}
      data={data}
      pagination={{
        // showJumper: true,
        pageItemStyle: { border: "1px solid #ccc", borderRadius: '5px' },
        activePageItemStyle: { backgroundColor: '#1890ff', color: '#fff' },
        sizeCanChange: true, size: 'mini', pageSize: pageSize,
        showTotal: (total, range) => `共 ${total} 条 第 ${range[1] / pageSize} / ${Math.ceil(total / pageSize)} 页`
      }}
    />
    }
    {/* ----------------第二个表格 */}
    {btnState ? <Table border borderCell
      rowKey={(record) => record.warningId}
      columns={tableData}
      data={tableBtnData}
      pagination={{
        // showJumper: true,
        pageItemStyle: { border: "1px solid #ccc", borderRadius: '5px' },
        activePageItemStyle: { backgroundColor: '#1890ff', color: '#fff' },
        sizeCanChange: true, size: 'mini', pageSize: pageSize,
        showTotal: (total, range) => `共 ${total} 条 第 ${range[1] / pageSize} / ${Math.ceil(total / pageSize)} 页`
      }}
    /> : null
    }

    {/* 立即处理弹窗框 */}
    <Modal
      className='handleBox'
      title='立即处理'
      visible={visible}
      onOk={() => handleBtn()}
      onCancel={() => { setVisible(false); handleFrom.clearFields() }}
      autoFocus={false}
      focusLock={true}
    >
      <Form style={{ width: 450 }} form={handleFrom}>
        <FormItem field='userName' label='处理人'
          rules={[{
            validator(value, cb) {
              if (value === '' || value === undefined) {
                return cb('必选')
              }
              return cb();
            }
          }]}
          labelCol={{ span: 7, offset: 0 }} wrapperCol={{ span: 16, offset: 0 }}>
          <Select
            placeholder='请选择'
            onFocus={userNameForm}
            options={selData}
            allowClear
          />
        </FormItem>
        <FormItem disabled field='processTime' label='处理时间' labelCol={{ span: 7, offset: 0 }} wrapperCol={{ span: 16, offset: 0 }}>
          <Input placeholder='请输入' />
        </FormItem>
        <FormItem field='processProblem' label='详细问题描述' required
          rules={[{
            validator(value, cb) {
              if (value === '' || value === undefined) {
                return cb('必填')
              } else if (value.length < 5) {
                return cb('不能少于5个字符')
              }
              return cb();
            }
          }]}
          labelCol={{ span: 7, offset: 0 }} wrapperCol={{ span: 16, offset: 0 }}>
          <TextArea placeholder='请输入备注' style={{ minHeight: 64, width: 350 }} />
        </FormItem>
        <FormItem field='processResult' label='详细结果描述' required
          rules={[{
            validator(value, cb) {
              if (value === '' || value === undefined) {
                return cb('必填')
              } else if (value.length < 5) {
                return cb('不能少于5个字符')
              }
              return cb();
            }
          }]}
          labelCol={{ span: 7, offset: 0 }} wrapperCol={{ span: 16, offset: 0 }}>
          <TextArea placeholder='请输入备注' style={{ minHeight: 64, width: 350 }} />
        </FormItem>
      </Form>
    </Modal>
  </div>
}

export default Equipment